package org.example.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.example.entity.Dish;
import org.example.entity.Category;
import org.example.mapper.DishMapper;
import org.example.mapper.CategoryMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.*;

@RestController
@RequestMapping("/dish")
@CrossOrigin(origins = "*")
public class DishController {

    @Autowired
    private DishMapper dishMapper;
    @Autowired
    private CategoryMapper categoryMapper;

    @GetMapping("/list")
    public Map<String, Object> getDishList(@RequestParam(required = false) Long categoryId,
                                           @RequestParam(required = false) Integer status) {
        LambdaQueryWrapper<Dish> wrapper = new LambdaQueryWrapper<>();
        if (categoryId != null) wrapper.eq(Dish::getCategoryId, categoryId);
        if (status != null) wrapper.eq(Dish::getStatus, status);
        wrapper.orderByDesc(Dish::getUpdateTime);
        List<Dish> list = dishMapper.selectList(wrapper);
        Map<String, Object> result = new HashMap<>();
        result.put("code", 1);
        result.put("msg", "查询成功");
        result.put("data", list);
        return result;
    }

    @GetMapping("/page")
    public Map<String, Object> getDishPage(
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int pageSize,
            @RequestParam(required = false) String name,
            @RequestParam(required = false) Long categoryId) {

        Page<Dish> pageInfo = new Page<>(page, pageSize);
        LambdaQueryWrapper<Dish> wrapper = new LambdaQueryWrapper<>();
        if (name != null && !name.isEmpty()) wrapper.like(Dish::getName, name);
        if (categoryId != null) wrapper.eq(Dish::getCategoryId, categoryId);
        wrapper.orderByDesc(Dish::getUpdateTime);
        dishMapper.selectPage(pageInfo, wrapper);

        // enrich records with categoryName
        List<Map<String, Object>> records = new ArrayList<>();
        for (Dish d : pageInfo.getRecords()) {
            Map<String, Object> row = new HashMap<>();
            row.put("id", d.getId());
            row.put("name", d.getName());
            row.put("image", d.getImage());
            row.put("price", d.getPrice());
            row.put("status", d.getStatus());
            row.put("updateTime", d.getUpdateTime());
            row.put("categoryId", d.getCategoryId());
            Category c = d.getCategoryId() == null ? null : categoryMapper.selectById(d.getCategoryId());
            row.put("categoryName", c == null ? "" : c.getName());
            records.add(row);
        }

        Map<String, Object> data = new HashMap<>();
        data.put("records", records);
        data.put("total", pageInfo.getTotal());
        data.put("current", pageInfo.getCurrent());
        data.put("size", pageInfo.getSize());

        Map<String, Object> result = new HashMap<>();
        result.put("code", 1);
        result.put("msg", "查询成功");
        result.put("data", data);
        return result;
    }

    @GetMapping("/{id}")
    public Map<String, Object> getDishById(@PathVariable Long id) {
        Dish dish = dishMapper.selectById(id);
        Map<String, Object> result = new HashMap<>();
        result.put("code", 1);
        result.put("msg", "查询成功");
        result.put("data", dish);
        return result;
    }

    @PostMapping
    public Map<String, Object> addDish(@RequestBody Map<String, Object> dish) {
        Dish entity = new Dish();
        entity.setName(String.valueOf(dish.get("name")));
        entity.setCategoryId(Long.valueOf(String.valueOf(dish.get("categoryId"))));
        entity.setPrice(new java.math.BigDecimal(String.valueOf(dish.get("price"))));
        entity.setCode(String.valueOf(dish.get("code")));
        entity.setImage(String.valueOf(dish.get("image")));
        entity.setDescription(String.valueOf(dish.get("description")));
        entity.setStatus(Integer.valueOf(String.valueOf(dish.getOrDefault("status", 1))));
        entity.setCreateTime(LocalDateTime.now());
        entity.setUpdateTime(LocalDateTime.now());
        entity.setCreateUser(1L);
        entity.setUpdateUser(1L);
        dishMapper.insert(entity);
        Map<String, Object> result = new HashMap<>();
        result.put("code", 1);
        result.put("msg", "添加成功");
        return result;
    }

    @PutMapping
    public Map<String, Object> updateDish(@RequestBody Map<String, Object> dish) {
        Dish entity = dishMapper.selectById(Long.valueOf(String.valueOf(dish.get("id"))));
        if (entity != null) {
            if (dish.get("name") != null) entity.setName(String.valueOf(dish.get("name")));
            if (dish.get("categoryId") != null) entity.setCategoryId(Long.valueOf(String.valueOf(dish.get("categoryId"))));
            if (dish.get("price") != null) entity.setPrice(new java.math.BigDecimal(String.valueOf(dish.get("price"))));
            if (dish.get("code") != null) entity.setCode(String.valueOf(dish.get("code")));
            if (dish.get("image") != null) entity.setImage(String.valueOf(dish.get("image")));
            if (dish.get("description") != null) entity.setDescription(String.valueOf(dish.get("description")));
            if (dish.get("status") != null) entity.setStatus(Integer.valueOf(String.valueOf(dish.get("status"))));
            entity.setUpdateTime(LocalDateTime.now());
            dishMapper.updateById(entity);
        }
        Map<String, Object> result = new HashMap<>();
        result.put("code", 1);
        result.put("msg", "修改成功");
        return result;
    }

    @DeleteMapping
    public Map<String, Object> deleteDish(@RequestParam String ids) {
        int affected = 0;
        for (String idStr : ids.split(",")) {
            if (idStr == null || idStr.isEmpty()) continue;
            Long id = Long.valueOf(idStr);
            affected += dishMapper.deleteById(id);
        }
        Map<String, Object> result = new HashMap<>();
        result.put("code", affected > 0 ? 1 : 0);
        result.put("msg", affected > 0 ? "删除成功" : "未删除任何记录");
        return result;
    }

    @PostMapping("/status/{status}")
    public Map<String, Object> updateStatus(@PathVariable int status, @RequestParam String ids) {
        for (String idStr : ids.split(",")) {
            if (idStr == null || idStr.isEmpty()) continue;
            Long id = Long.valueOf(idStr);
            Dish entity = dishMapper.selectById(id);
            if (entity != null) {
                entity.setStatus(status);
                entity.setUpdateTime(LocalDateTime.now());
                dishMapper.updateById(entity);
            }
        }
        Map<String, Object> result = new HashMap<>();
        result.put("code", 1);
        result.put("msg", "状态修改成功");
        return result;
    }
}

